package com.zat.mes.andrmes.dofun.qualitytest

import android.content.Intent
import android.media.RingtoneManager
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.contrarywind.view.WheelView
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.qualitytest.adapter.QualityPlanAdapter
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.DateUtil
import com.zat.mes.andrmes.utils.DisplayUtil
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.ReadCardUtils
import kotlinx.android.synthetic.main.activity_quality_plan.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.layout_title_right_date.*
import java.util.*

/**
 * 质检计划
 */
class QualityPlanActivity : BaseActivity() {

    private var qcModel: QcPlanViewModel? = null
    private lateinit var adpater: QualityPlanAdapter
    private var empId: Long = 0
    private var timePicker: TimePickerView? = null
    var selectedDate = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
    var showDate: String? = null
    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null

    override fun init() {
        initView()
        initData()
        //读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()
    }

    /**
     * 初始化RfId卡
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "rfid: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
                //跳转 onsiteActivity 处理 默认质检
                //质检
                val intentOnRecord = Intent(this, OnSiteActivity::class.java)
                intentOnRecord.putExtra(CompanionType.INTENT_EXTRA_RFID, it)
                //0 质检 1 巡检
                intentOnRecord.putExtra(CompanionType.INTENT_EXTRA_QCTYPE, 0)
                startBaseActivity(intentOnRecord)

            }
        });
    }

    /**
     * 刷卡监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    /**
     * 释放监听和数据
     */
    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

    /**
     * 初始化数据
     */
    private fun initData() {

        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        showDate = DateUtil.formatDate(Date(), DateUtil.FORMAT_b)
        setDateText()
        initDatePick()

        adpater = QualityPlanAdapter(R.layout.item_quality_plan)
        recyclerQualityPlan.layoutManager = LinearLayoutManager(this)
        recyclerQualityPlan.adapter = adpater
        loadModel()

    }

    /**
     * 初始化model
     */
    private fun loadModel() {
        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getQcPlanList()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it == null || it.size <= 0) {
                setEmptyVisible()
            } else {
                setEmptyGone()
            }
            adpater.setNewData(it)
        })

        requestData()
    }

    /**
     * 请求数据
     */
    private fun requestData() {
        qcModel?.loadQcPlanList(empId, selectedDate)
        showLoading()
    }

    /**
     * 初始化view
     */
    private fun initView() {
        setContentView(R.layout.activity_quality_plan)
        tVtitle.text = getString(R.string.title_quality_plan)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        rlRightComm.visibility = View.VISIBLE
        val inflate = LayoutInflater.from(this).inflate(R.layout.layout_title_right_date, null)
        rlRightComm.addView(inflate)
        val layoutParams: RelativeLayout.LayoutParams =
            inflate.layoutParams as RelativeLayout.LayoutParams
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
        layoutParams.rightMargin = DisplayUtil.dip2px(this, 30f)
        rlRightComm.setOnClickListener {
            timePicker?.show()
        }
    }

    /**
     * 初始化时间选择器
     */
    private fun initDatePick() {
        timePicker = TimePickerBuilder(this, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                if (date != null) {
                    selectedDate = DateUtil.formatDate(date, DateUtil.FORMAT_3)
                    showDate = DateUtil.formatDate(date, DateUtil.FORMAT_b)
                    setDateText()
                    requestData()

                }
            }

        }).setSubmitColor(ContextCompat.getColor(this, R.color.color_text_nomal))
            .setCancelColor(ContextCompat.getColor(this, R.color.color_text_nomal))
            .setTitleBgColor(ContextCompat.getColor(this, R.color.color_white))
            .setContentTextSize(18)
            .setLabel("", "", "", "", "", "")
            .setDividerType(WheelView.DividerType.WRAP)
            .setDividerColor(ContextCompat.getColor(this, R.color.color_theme))
            .setLineSpacingMultiplier(2.0f)
            .build()
    }

    /**
     * 设置时间
     */
    fun setDateText() {
        tvTimeTitleRight.text = showDate
    }
}
